package com.rts.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author:weizhang
 * @date: 2020-03-31
 * @modify:
 * @des: redis配置
 */
@Configuration
@EnableCaching
public class RedisConfig {

    /**
     * 设置数据存入redis 的序列化方式
     * RedisTemplate配置 在单独使用redisTemplate的时候 重新定义序列化方式
     * </br>redisTemplate序列化默认使用的jdkSerializeable,存储二进制字节码,导致key会出现乱码，所以自定义序列化类。
     *
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // jackson2JsonRedisSerializer序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * Springboot 2.x CacheManager配置
     * @param connectionFactory
     * @return
     */
    @Bean
    public CacheManager getRedisCacheManager(RedisConnectionFactory connectionFactory) {
        // 缓存空间 set 集合
        Set<String> cacheName = new HashSet<>();
        cacheName.add("10min");
        cacheName.add("30min");
        cacheName.add("60min");
        cacheName.add("180min");
        cacheName.add("720min");
        cacheName.add("1440min");
        cacheName.add("10080min");
        cacheName.add("max");

        RedisCacheConfiguration MinCacheConfig_10 = initRedisCacheConfig(10);    //10min 信息缓存配置
        RedisCacheConfiguration MinCacheConfig_30 = initRedisCacheConfig(30);    //30min 信息缓存配置
        RedisCacheConfiguration MinCacheConfig_60 = initRedisCacheConfig(60);   //60min 信息缓存配置
        RedisCacheConfiguration MinCacheConfig_180 = initRedisCacheConfig(180);   //180min 信息缓存配置
        RedisCacheConfiguration MinCacheConfig_720 = initRedisCacheConfig(720);    //720min 信息缓存配置
        RedisCacheConfiguration MinCacheConfig_1440 = initRedisCacheConfig(1440);    //720min 信息缓存配置
        RedisCacheConfiguration MinCacheConfig_10080 = initRedisCacheConfig(10080);    //10080min 信息缓存配置
        RedisCacheConfiguration MinCacheConfig_Max = initRedisCacheConfig(Integer.MAX_VALUE);    //720min 信息缓存配置

        Map<String, RedisCacheConfiguration> redisCacheConfigMap = new HashMap<>();
        redisCacheConfigMap.put("10min", MinCacheConfig_30);
        redisCacheConfigMap.put("30min", MinCacheConfig_30);
        redisCacheConfigMap.put("60min", MinCacheConfig_60);
        redisCacheConfigMap.put("180min", MinCacheConfig_180);
        redisCacheConfigMap.put("720min", MinCacheConfig_720);
        redisCacheConfigMap.put("1440min", MinCacheConfig_1440);
        redisCacheConfigMap.put("10080min", MinCacheConfig_10080);
        redisCacheConfigMap.put("max",MinCacheConfig_Max);
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
        //初始化RedisCacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
                .initialCacheNames(cacheName)   // 注意这两句的调用顺序，一定要先调用该方法设置初始化的缓存名，再初始化相关的配置
                .withInitialCacheConfigurations(redisCacheConfigMap)
                .build();
        return cacheManager;
    }

    /**
     * 初始化RedisCache的配置类
     * @param timeoutByMinute 过期时间，单位是分钟
     * @param prefixKey key前缀
     * @return
     */
    public RedisCacheConfiguration initRedisCacheConfig(long timeoutByMinute, String prefixKey){
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 关键点，spring cache的注解使用的序列化都从这来，没有这个配置的话使用的jdk自己的序列化，实际上不影响使用，只是打印出来不适合人眼识别
        RedisCacheConfiguration redisCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .entryTtl(Duration.ofMinutes(timeoutByMinute))
                .prefixKeysWith(prefixKey);

        return redisCacheConfig;
    }

    /**
     * 初始化RedisCache的配置类
     * @param timeoutByMinute 过期时间，单位是分钟
     * @return
     */
    public RedisCacheConfiguration initRedisCacheConfig(long timeoutByMinute){
        // 设置序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 关键点，spring cache的注解使用的序列化都从这来，没有这个配置的话使用的jdk自己的序列化，实际上不影响使用，只是打印出来不适合人眼识别
        RedisCacheConfiguration redisCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .entryTtl(Duration.ofMinutes(timeoutByMinute));

        return redisCacheConfig;
    }

}

